package com.liit.controller.func;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.liit.annotation.SystemLog;
import com.liit.controller.index.BaseController;
import com.liit.entity.DictFormMap;
import com.liit.entity.OrgInfoFormMap;
import com.liit.entity.PartyAttendFormMap;
import com.liit.entity.PartyFormMap;
import com.liit.entity.PartySignFormMap;
import com.liit.entity.WeixinUserFormMap;
import com.liit.mapper.DictMapper;
import com.liit.mapper.OrgInfoMapper;
import com.liit.mapper.PartyAttendMapper;
import com.liit.mapper.PartyMapper;
import com.liit.mapper.WeixinUserMapper;
import com.liit.plugin.PageView;
import com.liit.upload.UploadUtil;
import com.liit.util.Common;
import com.liit.util.DictUtils;
import com.liit.util.JsonUtils;
import com.liit.util.POIUtils;
import com.liit.util.PropertiesUtils;
import com.liit.util.RegionUtils;

import cn.liit.weixin.core.basic.accesstoken.AccessTokenSupport;
import cn.liit.weixin.qrcode.WeixinQrcode;
import cn.liit.weixin.templatemsg.utils.MsgUtil;

@Controller
@RequestMapping("/party/")
public class PartyController extends BaseController {
	@Inject
	private PartyMapper partyMapper;
	@Inject
	private WeixinUserMapper weixinUserMapper;
	@Inject
	private OrgInfoMapper orgInfoMapper;
	@Inject
	private PartyAttendMapper partyAttendMapper;
	@Inject
	private DictMapper dictMapper;
	
	@RequestMapping("listApplying")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("dict", DictUtils.getDictByType("PARTY"));
		return Common.BACKGROUND_PATH + "/func/listPartyApplying";
	}

	@RequestMapping("list")
	public String listHis(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("dict", DictUtils.getDictByType("PARTY"));
		model.addAttribute("partyType", DictUtils.getDictByType("PARTY_TYPE"));
		return Common.BACKGROUND_PATH + "/func/listParty";
	}

	@ResponseBody
	@RequestMapping("findByApplyingPage")
	public PageView findByApplyingPage(String pageNow, String pageSize) throws Exception {
		PartyFormMap partyFormMap = getFormMap(PartyFormMap.class);
		partyFormMap.put("status",Common.PARTY_STATUS_APPLY);
		Common.addRoleParameter(partyFormMap);
		Common.trimMap(partyFormMap);
		partyFormMap.put("orderby", "order by createTime desc");
		partyFormMap = toFormMap(partyFormMap,pageNow,pageSize,partyFormMap.getStr("orderby"));
		List<PartyFormMap> partys=partyMapper.findByPage(partyFormMap);
		for(int i=0;i<partys.size();i++){
			WeixinUserFormMap param=new WeixinUserFormMap();
			param.put("openid", partys.get(i).get("openid"));
			partys.get(i).put("openid", weixinUserMapper.findByWhere(param).get(0).get("nickname"));
		}
		pageView.setRecords(partys);
		return pageView;
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String pageNow, String pageSize) throws Exception {
		PartyFormMap partyFormMap = getFormMap(PartyFormMap.class);
		Common.addRoleParameter(partyFormMap);
		Common.trimMap(partyFormMap);
		partyFormMap.put("orderby", "order by createTime desc");
		partyFormMap = toFormMap(partyFormMap,pageNow,pageSize,partyFormMap.getStr("orderby"));
		List<PartyFormMap> partys=partyMapper.findByPage(partyFormMap);
		for(int i=0;i<partys.size();i++){
			WeixinUserFormMap param=new WeixinUserFormMap();
			param.put("openid", partys.get(i).get("openid"));
			partys.get(i).put("openid", weixinUserMapper.findByWhere(param).get(0).get("nickname"));
			
			OrgInfoFormMap orgInfo=new OrgInfoFormMap();
			orgInfo.put("id",partys.get(i).get("orgInfoId"));
			partys.get(i).put("orgInfoId",orgInfoMapper.findByWhere(orgInfo).get(0).get("orgName"));
		}
		pageView.setRecords(partys);
		return pageView;
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		WeixinUserFormMap weixin=Common.getWeixinUserInfo();
		OrgInfoFormMap org=new OrgInfoFormMap();
		org.put("id", weixin.get("orgInfoId"));
		model.addAttribute("dict", DictUtils.getDictByType("PARTY_TYPE"));
		model.addAttribute("orgName",orgInfoMapper.findByWhere(org).get(0).get("orgName"));
		
		return Common.BACKGROUND_PATH + "/system/party/updateParty";
	}
	
	@ResponseBody
	@RequestMapping("pass")
	@Transactional(readOnly = false)
	@RequiresPermissions("party:check:pass")
	@SystemLog(module = "活动管理", methods = "活动审核-审核通过")
	public String pass(String ids) throws Exception {
		logger.info("party pass param:" + ids);
		String[] idss=ids.split(",");
		Timestamp now = new Timestamp(System.currentTimeMillis());
		PartyFormMap record = new PartyFormMap();
		for (String id : idss) {
			record.put("id", id);
			record.put("status", Common.PARTY_STATUS_PASS);
			record.put("updateTime", now);
			record.put("accountName", SecurityUtils.getSubject().getPrincipal());
			/*永久有效二维码*/
			//party.put("qrCode", WeixinQrcode.genLimitQR(party.get("id").toString(), null, AccessTokenSupport.getAccess_token()));
			/*临时二维码*/
			record.put("qrCode", WeixinQrcode.genQR(2592000,record.get("id").toString(), AccessTokenSupport.getAccess_token()));
			partyMapper.editEntity(record);
			
			//添加积分
			//IntegralUtils.getInstance().partyPass(Integer.parseInt(id));
			
			// 发送模板消息
			PartyFormMap partyRecord = partyMapper.findbyFrist("id", id, PartyFormMap.class);
			sendTemplateMsg(partyRecord.getStr("openid"), "", partyRecord);
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("reject")
	@Transactional(readOnly = false)
	@RequiresPermissions("party:check:reject")
	@SystemLog(module = "活动管理", methods = "活动审核-审核拒绝")
	public String reject(String ids) throws Exception {
		logger.info("party reject param:" + ids);
		String[] idss=ids.split(",");
		Timestamp now = new Timestamp(System.currentTimeMillis());
		PartyFormMap record = new PartyFormMap();
		for (String id : idss) {
			record.put("id", id);
			record.put("status", Common.PARTY_STATUS_REJECT);
			record.put("updateTime", now);
			partyMapper.editEntity(record);
			
			// 发送模板消息
			PartyFormMap partyRecord = partyMapper.findbyFrist("id", id, PartyFormMap.class);
			sendTemplateMsg(partyRecord.getStr("openid"), "", partyRecord);
		}
		return "success";
	}
	/**
	 * 新增或修改商品信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("saveParty")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "活动管理", methods = "活动管理-新增活动")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String saveParty(Model model, RedirectAttributes redirectAttributes, MultipartHttpServletRequest request) throws Exception {
		SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		PartyFormMap party = getFileFormMap(PartyFormMap.class, request);
		UploadUtil.uploadImage((Map<String, MultipartFile>) party.get("FILES"), UploadUtil.UPLOAD_PATH + "party");
		party.put("openid",Common.getWeixinUserInfo().get("openid"));
		party.put("orgInfoId",Common.getWeixinUserInfo().get("orgInfoId"));
		party.put("createTime", simple.format(new Date()));
		party.put("updateTime", simple.format(new Date()));
		party.put("status", Common.PARTY_STATUS_APPLY);
		partyMapper.addEntity(party);
		party.put("codeNo", Common.format(new Date(), "yyyy") + String.format("%05d", party.get("id")));
		party.put("detail",party.get("detail").toString().replace("待生成",party.get("codeNo").toString()));
		
		partyMapper.editEntity(party);
		return "success";
	}
	
	@RequestMapping("download")
	public void download(String url, HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.reset();
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + System.currentTimeMillis() + ".jpg\"");  
		URL uri = new URL(url);
		URLConnection conn = uri.openConnection();
		conn.setDoInput(true);
		conn.connect();
		InputStream os = conn.getInputStream();
		OutputStream respOs = response.getOutputStream();
		int length ;
		while((length = os.read())!=-1){
			respOs.write(length);
		}
		respOs.flush();
		os.close();
		respOs.close();
		
	}
	@RequestMapping("viewUI")
	public String findByPage(Model model, String id) throws Exception {
		PartyFormMap record=partyMapper.findbyFrist("id",id,PartyFormMap.class);
		record.put("province", RegionUtils.getRegionNameById(record.getStr("province")));
		record.put("city", RegionUtils.getRegionNameById(record.getStr("city")));
		record.put("area", RegionUtils.getRegionNameById(record.getStr("area")));
		record.put("street", RegionUtils.getRegionNameById(record.getStr("street")));
		WeixinUserFormMap weixinUser = new WeixinUserFormMap();
		weixinUser.put("openid",record.get("openid"));
		record.put("openid",weixinUserMapper.findByWhere(weixinUser).get(0).get("nickname"));
		OrgInfoFormMap org=new OrgInfoFormMap();
		org.put("id", record.get("orgInfoId"));
		record.put("orgInfoId",orgInfoMapper.findByWhere(org).get(0).get("orgName"));
		
		DictFormMap dict=new DictFormMap();
		dict.put("type", "PARTY_TYPE");
		dict.put("value",record.get("type"));
		
		record.put("type", dictMapper.findByWhere(dict).get(0).get("label"));
		model.addAttribute("party", record);
		return Common.BACKGROUND_PATH + "/func/viewParty";
	}
	
	@RequestMapping("viewDetail")
	public String viewdetail(Model model,String id){
		model.addAttribute("partyId",id);
		return Common.BACKGROUND_PATH+"/func/viewPartyDetail";
	}
	
	@ResponseBody
	@RequestMapping("findPartyDetail")
	public PageView findPartyDetail(String pageNow, String pageSize,String id) throws Exception {
		PartyAttendFormMap partyAttend = new PartyAttendFormMap();
		partyAttend.put("partyId",id);
		partyAttend = toFormMap(partyAttend, pageNow, pageSize, partyAttend.getStr("orderby"));
		List<PartyAttendFormMap> plist=partyAttendMapper.findByPage(partyAttend);
		if(plist.size()>0){
			for(int i=0;i<plist.size();i++){
				WeixinUserFormMap param=new WeixinUserFormMap();
				param.put("openid", plist.get(i).get("openid"));
				plist.get(i).put("openid", weixinUserMapper.findByWhere(param).get(0).get("nickname"));
				PartyFormMap pform=new PartyFormMap();
				pform.put("id",plist.get(i).get("partyId"));
				plist.get(i).put("partyId",partyMapper.findByWhere(pform).get(0).get("subject"));
				
			}
		}
		pageView.setRecords(plist);
		return pageView;
	}
	
	@RequestMapping("/exportDetail")
	public void exportPerson(HttpServletRequest request, HttpServletResponse response,String partyId) throws IOException {
		String fileName = "";
		PartyAttendFormMap partyAttend = findHasHMap(PartyAttendFormMap.class);
		String exportData = partyAttend.getStr("exportData");// 列表头的json字符串
		partyAttend.put("partyId", partyId);
		
		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);
		List<PartyAttendFormMap> lis = partyAttendMapper.findByWhere(partyAttend);//userMapper.findUserPage(userFormMap);
		PartyFormMap party=new PartyFormMap();
		party.put("id",partyId);
		
		fileName=partyMapper.findByWhere(party).get(0).get("subject").toString();
		
		if(lis.size()>0){
			for(int i=0;i<lis.size();i++){
				WeixinUserFormMap param=new WeixinUserFormMap();
				param.put("openid", lis.get(i).get("openid"));
				lis.get(i).put("openid", weixinUserMapper.findByWhere(param).get(0).get("nickname"));
				
				PartyFormMap pform=new PartyFormMap();
				pform.put("id",lis.get(i).get("partyId"));
				lis.get(i).put("partyId",partyMapper.findByWhere(pform).get(0).get("subject"));
				
			}
		}
		POIUtils.exportToExcel(response, listMap, lis, fileName);
	}
	@RequestMapping("/exportParty")
	public void exportParty(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "活动信息";
		PartyFormMap partyFormMap = findHasHMap(PartyFormMap.class);
		String exportData = partyFormMap.getStr("exportData");// 列表头的json字符串
		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);
		listMap.remove(0);
		Common.addRoleParameter(partyFormMap);
		Common.trimMap(partyFormMap);
		partyFormMap.put("orderby", "order by createTime desc");
		List<PartyFormMap> partys=partyMapper.findByWhere(partyFormMap);
		for(int i=0;i<partys.size();i++){
			WeixinUserFormMap param=new WeixinUserFormMap();
			param.put("openid", partys.get(i).get("openid"));
			partys.get(i).put("openid", weixinUserMapper.findByWhere(param).get(0).get("nickname"));
			
			OrgInfoFormMap orgInfo=new OrgInfoFormMap();
			orgInfo.put("id",partys.get(i).get("orgInfoId"));
			partys.get(i).put("orgInfoId",orgInfoMapper.findByWhere(orgInfo).get(0).get("orgName"));
			
			DictFormMap dform=new DictFormMap();
			dform.put("type", "PARTY_TYPE");
			dform.put("value", partys.get(i).get("type"));
			
			if(!"".equals(partys.get(i).get("type"))&&partys.get(i).get("type")!=null){
				partys.get(i).put("type",dictMapper.findByWhere(dform).get(0).get("label"));
			}
			
			if("0".equals(partys.get(i).get("isRecommend").toString())){
				partys.get(i).put("isRecommend","未推荐");
			}else{
				partys.get(i).put("isRecommend","重点推荐");
			}
			
			dform.put("type", "PARTY");
			dform.put("value",partys.get(i).get("status"));
			partys.get(i).put("status",dictMapper.findByWhere(dform).get(0).get("label"));
			
		}
		POIUtils.exportToExcel(response, listMap, partys, fileName);
	}
	/**
	 * 删除活动信息
	 * 1根据活动id，删除活动参与人t_party_attend表的纪录。
		2根据活动id删除活动信息，t_party表纪录。
	 */
	@ResponseBody
	@RequestMapping("deleteEntity")
	// 需要事务操作必须加入此注解
	@Transactional(readOnly = false)
	// 凡需要处理业务逻辑的.都需要记录操作日志
	@SystemLog(module = "活动管理", methods = "删除活动")
	@RequiresRoles(logical = Logical.OR, value = { "admin", "branch", "street" })
	public String deleteEntity() throws Exception {
		String[] ids =getPara("ids").split(",");
		Boolean isTrue=false;
		for (String id : ids) {
			PartyAttendFormMap paf=new PartyAttendFormMap();
			paf.put("partyId",id);
			List<PartyAttendFormMap> paList=partyAttendMapper.findByWhere(paf);
			if(paList.size()>0){
				isTrue=true;
				break;
			}
		}
		if(isTrue){
			return "fail";
		}else{
			for (String id : ids) {
				PartyFormMap pm=partyMapper.findbyFrist("id", id,PartyFormMap.class);
				deleteFile(UploadUtil.UPLOAD_PATH + "party"+"/"+pm.getStr("partyImage"));
				partyMapper.deleteByAttribute("id", id, PartyFormMap.class);
				partyMapper.deleteByAttribute("partyId", id, PartySignFormMap.class);
			}
			return "success";
		}
	}
	
	@ResponseBody
	@RequestMapping("recommendEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "活动管理", methods = "推荐活动")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String recommendEntity() throws Exception {
		String[] ids = getPara("ids").split(",");
		for (String id : ids) {
			PartyFormMap party=partyMapper.findbyFrist("id",id, PartyFormMap.class );
			party.put("isRecommend",1);
			partyMapper.editEntity(party);
		}
		return "success";
	}
	/**
	 * 取消推荐活动信息
	 */
	@ResponseBody
	@RequestMapping("unRecommendEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "活动管理", methods = "删除活动")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String unRecommendEntity() throws Exception {
		String[] ids = getPara("ids").split(",");
		for (String id : ids) {
			PartyFormMap party=partyMapper.findbyFrist("id",id, PartyFormMap.class );
			party.put("isRecommend",0);
			partyMapper.editEntity(party);
		}
		return "success";
	}
	
	@ResponseBody
	@RequestMapping("findPartySign")
	public PageView findPartySign(String pageNow, String pageSize,String id) throws Exception {
		PartySignFormMap partyFormMap = getFormMap(PartySignFormMap.class);
		partyFormMap.put("partyId", id);
		partyFormMap.put("status", 0);
		partyFormMap = toFormMap(partyFormMap,pageNow,pageSize,partyFormMap.getStr("orderby"));
		List<PartySignFormMap> partys=partyMapper.findByPage(partyFormMap);
		for(PartySignFormMap partySign : partys){
			WeixinUserFormMap param = weixinUserMapper.findbyFrist("openid", partySign.getStr("openid"), WeixinUserFormMap.class);
			partySign.put("nickName", param.get("nickname"));
			partySign.put("name", weixinUserMapper.findByWhere(param).get(0).get("name"));
			partySign.put("mobile", weixinUserMapper.findByWhere(param).get(0).get("mobile"));
			partySign.put("headImgUrl", param.get("headImgUrl"));
		}
		pageView.setRecords(partys);
		return pageView;
	}
	 public void deleteFile(String name) throws IOException{
		 File fis =new File(name);
		 fis.delete();
	 }
	 
	/**
	 * 发送活动审核模板消息
	 * 
	 * @param openid
	 * @param url
	 * @param partyFormMap
	 */
	private static void sendTemplateMsg(String openid, String url, PartyFormMap partyFormMap) {
		String first = null;
		String[] keywords = null;
		if (partyFormMap.getInt("status") == Common.PARTY_STATUS_PASS) {
			first = "您好，恭喜您！您发布的活动【" + partyFormMap.getStr("subject") + "】已经通过审核。\\n\\n"
					+ "【G绿色伙伴】免费为社会组织提供线下活动的线上全流程服务（活动发布—报名—签到—评价等）。\\n\\n"
					+ "进入菜单【机构入口】——点击【活动发布】发布各类活动信息";
			keywords = new String[] { partyFormMap.getStr("subject"), "审核通过" };
		} else if (partyFormMap.getInt("status") == Common.PARTY_STATUS_REJECT) {
			first = "您好！您发布的活动【" + partyFormMap.getStr("subject") + "】审核失败，原因可能是：活动类型、活动主题、活动详情不相符，请您核对后，填写完整的信息。\\n\\n"
					+ "请您进入菜单【机构入口】——点击【活动发布】（填写完整的信息后）发布各类活动信息。\\n\\n"
					+ "【G绿色伙伴】免费为社会组织提供线下活动的线上全流程服务（活动发布—报名—签到—评价等）";
			keywords = new String[] { partyFormMap.getStr("subject"), "审核拒绝" };
		}
		MsgUtil.sendTemplateMsg(AccessTokenSupport.getAccess_token(), openid, url, PropertiesUtils.findPropertiesKey("templateid.org"), first, keywords, "");
	}
}
